/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.biz;

import cw.controller.UserJpaController;
import cw.ulti.CalendarUlti;
import cw.ulti.CryptoLibrary;
import cw.ulti.Helper;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author VinhTC
 */
public class UserBiz {

    UserJpaController uController = new UserJpaController();
    CryptoLibrary crypto = new CryptoLibrary();
    public UserBiz() {
    }

    /**
     * getUserByEmail
     * @param email
     * @return
     */
    public cw.entity.User getUserByEmail(String email) {
        cw.entity.User user = null;
        try {
            user = uController.getUserByEmail(email);
        } catch (Exception ex) {
            Logger.getLogger(UserBiz.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return user;
    }

    /**
     * login
     * @param username
     * @param pass
     * @return
     */
    public boolean login(String uNameEncrypted, String passEncrypted) {
        try {
            boolean result = false;
            cw.entity.User user = new cw.entity.User();
            user = uController.getUserByUserNameAndPassword(crypto.decrypt(uNameEncrypted), crypto.decrypt(passEncrypted));
            if (user != null) {
                if (user.getIsAdmin() && user.getStatus()) {
                    CalendarUlti cal = new CalendarUlti();
                    Date date = new Date();
                    user.setLastAccess(cal.convertDateTime(date.getTime()));
                    uController.edit(user);
                    result = true;
                }
            }
            return result;
        } catch (Exception e) {
            Logger.getLogger(UserBiz.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }
    }

    /**
     * getUserByUserName
     * @param username
     * @return User
     */
    public cw.entity.User getUserByUserName(String username) {
        cw.entity.User user = null;
        try {
            user = uController.getUserByUserName(username.trim());
        } catch (Exception ex) {
            Logger.getLogger(UserBiz.class.getName()).log(Level.SEVERE, null, ex);
        }

        return user;
    }
}
